package com.guigu.health.realm;

import com.guigu.health.pojo.User;
import com.guigu.health.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * @ClassName:HealthRealm
 * @Description:自定义realm验证授权
 * @Author:longtao
 * @Date:2021/3/26
 * @Version:1.0
 */
public class HealthRealm extends AuthorizingRealm {
    @Autowired
    public UserService userService;


    /**
     * 为登录用户授予权限和角色
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 验证当前登录用户
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        /**
         * 获取用户名
         */
        String userName= (String) token.getPrincipal();
        /**
         * 获取user对象
         */
        User user=userService.loginUser(userName);

        //4.用户存在则进行密码校验，否则，抛出异常：系统管理员不存在;
        if (user!=null){
            /**
             * 当前realm对象的name
             */
            String realmName=this.getName();
            /**
             * 获取随机盐
             */
            String salt=userService.getSalt(userName);
            ByteSource source=ByteSource.Util.bytes(salt);
            /**
             * 参数分别为:
             * 1.数据库中的账号
             * 2.数据库中的密码
             * 3.随机盐
             * 4.当前realm对象的名字
             */
            AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),source,realmName);
       return authenticationInfo;
        }else{
            //没找到帐号
            throw new UnknownAccountException("不存在该用户");
        }
    }
}
